<template>
  <div>
    <a-row class="seach-row">
      <a-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
        <a-form-item label="优惠券搜索" style="display: flex;align-items: center">
          <a-input v-model="name" placeholder="请输入优惠券名称" style="width: 100%"/>
        </a-form-item>
      </a-col>
      <a-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
        <a-form-item label="领取方式" style="display: flex;align-items: center">
          <a-select v-model="receive" placeholder="请选择" style="width: 100%;min-width: 200px">
            <a-select-option value="all">全部</a-select-option>
            <a-select-option value="good">用户领取</a-select-option>
            <a-select-option value="bad">系统发放</a-select-option>
          </a-select>
        </a-form-item>
      </a-col>
      <a-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
        <a-form-item label="使用范围" style="display: flex;align-items: center">
          <a-select v-model="status" placeholder="请选择" style="width: 100%;min-width: 200px">
            <a-select-option value="all">全部</a-select-option>
            <a-select-option value="good">全场通用</a-select-option>
            <a-select-option value="bad">指定商品可用</a-select-option>
            <a-select-option value="bad">指定分类可用</a-select-option>
          </a-select>
        </a-form-item>
      </a-col>
      <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
        <a-button type="primary" class="search-btn" @click="filterDataSource">查询</a-button>
        <a-button class="reset-btn" @click="resetFilters">重置</a-button>
      </a-col>
    </a-row>

    <div class="content">
      <!-- Tab栏 -->
      <a-tabs :active-key="defaultActive" @change="handleChange">
        <a-tab-pane key="all" :tab="`全部（${allCount} ）`"></a-tab-pane>
        <a-tab-pane key="pending" :tab="`未开始（${pendingCount}）`"></a-tab-pane>
        <a-tab-pane key="replied" :tab="`进行中（${repliedCount}）`"></a-tab-pane>
        <a-tab-pane key="end" :tab="`已结束（${endCount}）`"></a-tab-pane>
      </a-tabs>
      <a-button type="primary" @click="handleAddBtn" class="add-btn">新增优惠券</a-button>
      <!-- 表格栏 -->
      <a-table :data-source="filteredData" :columns="columns" rowKey="id" class="tab-cont"
               :scroll="{ x: 'max-content' }">
        <template slot="action" slot-scope="text,record">
          <a-button type="link" @click="handleDetail(record)">编辑</a-button>
          <a-button type="link">删除</a-button>
        </template>
      </a-table>
      <a-modal
          title="新增优惠券"
          :visible="addModalVisible"
          @ok="handleAddOk"
          @cancel="handleAddCancel">
        <a-form-item label="优惠券名称">
          <a-input v-model="currentCoupon.name"/>
        </a-form-item>
        <a-form-item label="优惠价格">
          <a-input v-model="currentCoupon.money"/>
        </a-form-item>
        <a-form-item label="兑换积分">
          <a-input v-model="currentCoupon.creditSexChange"/>
        </a-form-item>
        <a-form-item label="领券时间">
          <a-range-picker v-model="currentCoupon.Time" style="width: 24.5vw"/>
        </a-form-item>
        <a-form-item label="优惠券状态">
          <a-select v-model="currentCoupon.status" style="width: 24.5vw">
            <a-select-option value="进行中">进行中</a-select-option>
            <a-select-option value="未开始">未开始</a-select-option>
            <a-select-option value="已结束">已结束</a-select-option>
          </a-select>
        </a-form-item>
      </a-modal>
      <a-modal
          title="编辑优惠券"
          :visible="detailModalVisible"
          @ok="handleCancel"
          @cancel="handleCancel">
        <a-form-item label="优惠券名称">
          <a-input v-model="currentCoupon.name"/>
        </a-form-item>
        <a-form-item label="领券时间">
          <a-range-picker v-model="currentCoupon.Time" style="width: 24.5vw"/>
        </a-form-item>
        <a-form-item label="发放数量">
          <a-input v-model="currentCoupon.sendTotalType"/>
        </a-form-item>
        <a-form-item label="优惠券状态">
          <a-select v-model="currentCoupon.status" style="width: 24.5vw">
            <a-select-option value="进行中">进行中</a-select-option>
            <a-select-option value="未开始">未开始</a-select-option>
            <a-select-option value="已结束">已结束</a-select-option>
          </a-select>
        </a-form-item>
      </a-modal>
    </div>
  </div>
</template>

<script>
import {Modal} from 'ant-design-vue';
import 'ant-design-vue/dist/antd.css';
import axios from "axios";
import moment from 'moment';

export default {
  components: {
    'a-modal': Modal,
  },
  data() {
    return {
      name: '',
      receive: 'all',
      status: 'all',
      pendingCount: 0,
      repliedCount: 0,
      endCount: 0,
      allCount: 0,  // 添加这个属性来计算全部数量
      defaultActive: 'all',
      filteredData: [],  // 过滤后的数据
      detailModalVisible: false,// 详情弹窗
      addModalVisible: false,// 新增弹窗
      currentCoupon: {},//当前操作的优惠券
      dataSource: [
        {
          id: '1',
          name: '优惠券1',
          getType: '用户领取',
          getTimeStart: '2023-06-01 12:00:00——2023-06-30 00:00:00',
          getTimeEnd: '2023-06-01 12:00:00——2023-06-30 00:00:00',
          sendTotalType: 100,
          creditSexChange: 50,
          status: '进行中',
          createTime: '2023-06-01 00:00:00',
        },
        {
          id: '2',
          name: '优惠券2',
          receive: '用户领取',
          getTimeStart: '2023-06-01 12:00:00——2023-06-30 00:00:00',
          getTimeEnd: '2023-06-01 12:00:00——2023-06-30 00:00:00',
          sendTotalType: 100,
          creditSexChange: 50,
          status: '未开始',
          createTime: '2023-06-01 00:00:00',
        },
        {
          id: '3',
          name: '优惠券3',
          receive: '用户领取',
          getTimeStart: '2023-06-01 12:00:00——2023-06-30 00:00:00',
          getTimeEnd: '2023-06-01 12:00:00——2023-06-30 00:00:00',
          sendTotalType: 100,
          creditSexChange: 50,
          status: '已结束',
          createTime: '2023-06-01 00:00:00',
        },
      ],
      columns: [
        {
          title: '编号',
          dataIndex: 'id',
          key: 'id',
          width: '110px',
        },
        {
          title: '优惠券名称',
          dataIndex: 'name',
          key: 'name',
          width: '110px',
        },
        {
          title: '优惠价格',
          dataIndex: 'money',
          key: 'money',
          width: '70px',
        },
        {
          title: '领券时间',
          dataIndex: 'Time',
          key: 'Time',
          width: '130px',
        },
        {
          title: '发放数量',
          dataIndex: 'sendTotalType',
          key: 'sendTotalType',
          width: '110px',
        },
        {
          title: '兑换所需积分',
          dataIndex: 'creditSexChange',
          key: 'creditSexChange',
          width: '110px',
        },
        {
          title: '优惠券状态',
          dataIndex: 'status',
          key: 'status',
          width: '110px',
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          key: 'createTime',
          width: '120px',
        },
        {
          title: '操作',
          key: 'action',
          scopedSlots: {customRender: 'action'},
          width: '200px',
          fixed: 'right',
        },
      ],
    };
  },
  methods: {
    clearForm() {
      // 重置表单数据
      this.currentCoupon = {
        name: '',
        money: '',
        creditSexChange: '',
        Time: null,
        status: '进行中' // 默认值
      };
    },
    async fetchcoupon() {
      try {
        const response = await axios.get(`${window.location.protocol}//${window.location.hostname}:8080/api/coupon/infoAllCouponAll`, {
          headers: {
            Authorization: `Bearer ` + localStorage.getItem('token')
          }
        });

        if (response.data.code === 200) {
          const orderData = response.data.data.reverse();
          for (let i = 0; i < orderData.length; i++) {
            orderData[i].Time = orderData[i].getTimeStart + "——" + orderData[i].getTimeEnd;
          }
          this.dataSource = orderData;
          console.log(this.dataSource)
          // this.filteredDataSource = [...orderData];
          // this.pagination.total = orderData.length;
          this.filterDataSource(); // 切换Tab时调用过滤方法
          this.updateCounts();
        } else {
          console.error('获取订单信息失败:', response.data.msg);
        }
      } catch (error) {
        console.error('请求失败:', error);
      }
    },
    async fetchadd(data) {
      try {
        const response = await axios.post(`${window.location.protocol}//${window.location.hostname}:8080/api/coupon/insert`, data, {
          headers: {
            Authorization: `Bearer ` + localStorage.getItem('token')
          }
        });

        if (response.data.code === 200) {
          this.$message.success('新增成功');
        } else {
          this.$message.error('新增失败');
        }
      } catch (error) {
        console.error('新增请求失败:', error);
      }
    },
    // Tab栏切换时触发的函数
    handleChange(key) {
      this.defaultActive = key;
      this.filterDataSource(); // 切换Tab时调用过滤方法
    },
    // 过滤数据
    filterDataSource() {
      let filtered = [...this.dataSource]; // 克隆原始数据

      // 根据当前Tab过滤数据
      switch (this.defaultActive) {
        case 'all':
          break;
        case 'pending':
          filtered = filtered.filter(item => item.status === '未开始');
          break;
        case 'replied':
          filtered = filtered.filter(item => item.status === '进行中');
          break;
        case 'end':
          filtered = filtered.filter(item => item.status === '已结束');
          break;
        default:
          break;
      }

      // 根据搜索条件进一步过滤
      if (this.name && this.name !== '') {
        filtered = filtered.filter(item => item.name.includes(this.name));
      }
      if (this.receive !== 'all') {
        filtered = filtered.filter(item => item.receive === this.receive);
      }
      if (this.status !== 'all') {
        filtered = filtered.filter(item => item.status === this.status);
      }

      // 更新过滤后的数据
      this.filteredData = filtered;

      // 更新数据统计
      // this.updateCounts();
    },
    // 更新统计数量
    updateCounts() {
      this.allCount = this.filteredData.length;
      this.pendingCount = this.filteredData.filter(item => item.status === '未开始').length;
      this.repliedCount = this.filteredData.filter(item => item.status === '进行中').length;
      this.endCount = this.dataSource.filter(item => item.status === '已结束').length;
    },
    // 重置搜索条件
    resetFilters() {
      this.name = '';
      this.receive = 'all';
      this.status = 'all';
      this.filterDataSource();
    },
    //打开新增模态框
    handleAddBtn() {
      this.clearForm();  // 处理完后清空表单
      this.addModalVisible = true;
    },
    //关闭新增模态框
    handleAddOk() {
      // 检查 moment 对象并进行格式化
      const startTime = this.currentCoupon.Time[0]
          ? this.currentCoupon.Time[0].format('YYYY-MM-DD HH:mm:ss')
          : '';  // 如果没有值，默认是空字符串

      const endTime = this.currentCoupon.Time[1]
          ? this.currentCoupon.Time[1].format('YYYY-MM-DD HH:mm:ss')
          : '';  // 如果没有值，默认是空字符串

      // 将格式化后的时间赋值给 getTimeStart 和 getTimeEnd
      const data = {
        creditSexChange: this.currentCoupon.creditSexChange,
        money: this.currentCoupon.money,
        name: this.currentCoupon.name,
        status: this.currentCoupon.status,
        getTimeStart: startTime,
        getTimeEnd: endTime,
        getType: "用户领取",
        isDelete: "否",
        useGoodsIds: 1,
        useGoodsType: "全部商品",
        sendTotalType: "无限数量"
      }

      this.fetchadd(data).then(() => {
        location.reload()
      })
      this.addModalVisible = false;
    },
    handleAddCancel() {
      this.addModalVisible = false;
    },
    //打开编辑模态框
    handleDetail(record) {
      // 处理时间格式：将字符串分割并转为 moment 对象
      if (record.Time) {
        const timeArray = record.Time.split('——'); // 根据 '——' 分割字符串
        if (timeArray.length === 2) {
          record.Time = [
            moment(timeArray[0], 'YYYY-MM-DD HH:mm:ss'),
            moment(timeArray[1], 'YYYY-MM-DD HH:mm:ss')
          ];
        }
      }
      this.currentCoupon = record;
      this.detailModalVisible = true;
    },
    handleCancel() {
      this.detailModalVisible = false;

      // 判断是否需要格式化时间
      if (this.currentCoupon.Time && this.currentCoupon.Time.length === 2) {
        const startTime = this.currentCoupon.Time[0].format('YYYY-MM-DD HH:mm:ss');
        const endTime = this.currentCoupon.Time[1].format('YYYY-MM-DD HH:mm:ss');

        // 重新合并成原始格式
        this.currentCoupon.Time = `${startTime}——${endTime}`;
      }
      // 如果有需要，可以在这里清理或重置数据
      this.currentCoupon = {};  // 例如，清空当前记录
    },
  },
  mounted() {
    // 初始加载时过滤数据
    // this.filterDataSource();
    this.fetchcoupon()
  },
};
</script>

<style scoped>
.seach-row {
  padding: 16px;
  border-radius: 4px;
  background-color: white;
}

.reset-btn {
  margin-left: 8px;
}

.content {
  margin-top: 16px;
  padding: 16px;
  border-radius: 4px;
  background-color: white;
}

.tab-cont {
  max-width: 100%;
  overflow-x: auto;
}

.add-btn {
  margin-bottom: 16px;
}
</style>